package com.fh.controller.dog.manage;


import com.fh.controller.base.BaseController;
import com.fh.dao.redis.RedisDao;
import com.fh.dao.redis.impl.RedisDaoImpl;
import com.fh.entity.Page;
import com.fh.entity.system.User;
import com.fh.service.dog.impl.CTitleServiceImpl;
import com.fh.util.BaseUtil;
import com.fh.util.Const;
import com.fh.util.DateUtil;
import com.fh.util.PageData;
import com.fh.util.layui.DataUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 文章
 */
@Controller
@RequestMapping(value = "/cTitle")
public class CTitleController extends BaseController {
    //spring  依赖注入
    @Autowired
    private CTitleServiceImpl cTitleService;
    @Autowired
    private RedisDao redisDaoImpl;


    /**
     * @Title: 查询 文章
     * @reason
     * @author :  陈豪
     * @date 2018/6/6
     */

    @RequestMapping(value = "/findById")
    @ResponseBody
    public PageData findById(HttpServletRequest request) throws Exception {
        PageData pageData = this.getPageData();


        try {
            User user = BaseUtil.getSession(new User(), request, Const.SESSION_USER);


            PageData pdData = cTitleService.findById(pageData);
            pageData.put("data", pdData);
            pageData.put("code", "00");
            pageData.put("msg", "查询成功");
        } catch (Exception e) {
            pageData.put("code", "01");
            pageData.put("msg", "查询失败");
            e.printStackTrace();
        }

        return pageData;
    }


    /**
     * @Title: 文章新增
     * @reason 文章新增
     * @author :  陈豪
     * @date 2018/5/23
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public PageData save(HttpServletRequest request) throws Exception {
        PageData pageData = this.getPageData();

        HttpSession session = request.getSession();
        //获得jedis

        try {
            User user = BaseUtil.getSession(new User(), request, Const.SESSION_USER);

            if (StringUtils.isBlank(pageData.getString("id"))) {
                String uuid = this.get32UUID();
                pageData.put("id", uuid);
                pageData.put("create_date", DateUtil.getTime());
                pageData.put("update_date", DateUtil.getTime());
                pageData.put("create_by", user.getUSER_ID());
                pageData.put("update_by", user.getUSER_ID());
                cTitleService.save(pageData);

                redisDaoImpl.addMap(uuid, pageData);
            } else {
                pageData.put("id", pageData.getString("id"));
                pageData.put("update_date", DateUtil.getTime());
                pageData.put("update_by", user.getUSER_ID());
                cTitleService.update(pageData);
                Map<String, String> map = redisDaoImpl.getMap(pageData.getString("id"));
                redisDaoImpl.addMap(pageData.getString("id"), redisUpdate(map, pageData));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        pageData.put("code", "00");
        pageData.put("msg", "保存成功");
        return pageData;
    }

    /**
     * @Title: 判断 redis 的数据 是否进行修改
     * @reason
     * @author :  陈豪
     * @date 2018/6/11
     */
    public Map redisUpdate(Map map, PageData pageData) {


        String keys = "id,keyType,pkey,is_del,type,text,is_open,title,create_date,update_date,create_by,sort,update_by";
        String[] split = keys.split(",");
        for (String key :
                split) {
            if(StringUtils.isNotBlank(pageData.getString(key))){
                if(!map.get(key).toString().equals(pageData.getString(key))){
                    map.put(key,pageData.getString(key));
                }

            }

        }
        return map;

    }


    @RequestMapping(value = "/list")
    @ResponseBody
    public String list(Page page) throws Exception {
        PageData pd = this.getPageData();

        String data = "";
        try {

            page.setPd(pd);
            DataUtil.setPage(page, pd);
            //只要父级数据
            List<PageData> list = cTitleService.list(page);
            //只要子集数据
            List<PageData> sublevellist = cTitleService.findlist(pd);
            //树 级 数据 整合
            levelList(list, sublevellist);


            data = DataUtil.getJsonData(page, list);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return data;
    }

    /**
     * fList:  父list  zlist  子list
     *
     * @Title: 树级 结构  整理
     * @reason
     * @author :  陈豪
     * @date 2018/5/29
     */
    public List<PageData> levelList(List<PageData> fList, List<PageData> zlist) {
        //返回 list

        List<PageData> allList = new ArrayList<PageData>();
        for (PageData pageData : fList) {
            //有的时候还是分不清  == 和equals,   每次都是知道==  对比的是值， equals 对比的是对象，但是做的时候就是  嘎嘎  拿出来的 不知道是值还是对象
            //pkey  是父级 字段， pkey==1 的时候 是 父级

            for (PageData sublevelPd : zlist) {
                if (sublevelPd.getString("pkey").equals(pageData.getString("keyType"))) {
                    if (!pageData.containsKey("children")) {
                        allList.add(sublevelPd);
                        //扔进 子集数据
                        pageData.put("children", allList);
                        //判断是否存在 ， 如果不存在  就是第一次向父级扔进子集数据
                    } else {
                        List<PageData> children = (List<PageData>) pageData.get("children");
                        children.add(sublevelPd);
                    }
                }

            }


        }
        return fList;
    }






    @RequestMapping(value = "/qlist")
    @ResponseBody
    public List qlist(Page page) throws Exception {
        PageData pd = this.getPageData();
        List<PageData>  list=new ArrayList<PageData>();
        String data = "";
        try {

            page.setPd(pd);
            DataUtil.setPage(page, pd);
            //只要父级数据
            list = cTitleService.list(page);
            //只要子集数据
            List<PageData> sublevellist = cTitleService.findlist(pd);
            //树 级 数据 整合
            levelList(list, sublevellist);

        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return list;
    }

}
